package cn.melonlib.apis.support.comp.scans;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.melonlib.apis.support.annos.ApiModule;
import cn.melonlib.apis.support.comp.proxy.ApiRequestProxyFactory;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Setter
@Component
public class ApiModuleScanner implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Value("${apis.module.packages:cn.com.qtgl.apis}")
    private List<String> apiModulePackages=List.of("cn.com.qtgl.apis");

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        apiModulePackages.stream().flatMap(p->ClassUtil.scanPackageByAnnotation(p, ApiModule.class).stream())
        .filter(Class::isInterface).forEach(cls->{
                    BeanDefinitionBuilder builder=BeanDefinitionBuilder.genericBeanDefinition(cls);
                    GenericBeanDefinition beanDefinition=(GenericBeanDefinition)builder.getRawBeanDefinition();
                    beanDefinition.getPropertyValues().add("interfaceClass",beanDefinition.getBeanClassName());
                    beanDefinition.getPropertyValues().add("applicationContext",applicationContext);
                    beanDefinition.setBeanClass(ApiRequestProxyFactory.class);
                    beanDefinition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
                    ApiModule apiModule=AnnotationUtils.findAnnotation(cls,ApiModule.class);
                    String beanName= StringUtils.defaultIfBlank(apiModule.value(),StrUtil.removePreAndLowerFirst(cls.getSimpleName(),0)+"ApiModule");
                    beanDefinitionRegistry.registerBeanDefinition(beanName,beanDefinition);
        });
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }

}
